import yaml
import os
import tempfile
from django.db import models
from project.models import Project

class Interface(models.Model):
    """接口信息模型"""
    name = models.CharField('接口名称', max_length=32)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    method = models.CharField('', max_length=8)
    url = models.CharField('', max_length=255)
    params = models.JSONField('查询参数', blank=True, default=dict)
    data = models.JSONField('表单参数', blank=True, default=dict)
    json = models.JSONField('JSON参数', blank=True, default=dict)
    cookies = models.JSONField('Cookies', blank=True, default=dict)
    headers = models.JSONField('请求头', blank=True, default=dict)

    class Meta:
        verbose_name = '接口'
        verbose_name_plural = '接口列表'  # Admin 中显示的名称（复数）

    def __str__(self):
        return f"{self.method} {self.url}"  # 示例：GET /api/login

class Case(models.Model):
    """接口用例"""
    PRIORITY_CHOICES = [
        ('HIGH', '高'),
        ('MEDIUM', '中'),
        ('LOW', '低'),
    ]
    
    name = models.CharField('用例名称', max_length=32)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    interface = models.ForeignKey(Interface, on_delete=models.CASCADE, blank=True, null=True)
    title = models.CharField('用例标题', max_length=200, default='')
    description = models.TextField('用例描述', default='')
    url = models.CharField('请求地址', max_length=255, default='')
    method = models.CharField('请求方法', max_length=10, default='GET')
    headers = models.JSONField('请求头', blank=True, default=dict)
    params = models.JSONField('请求参数', blank=True, default=dict)
    body = models.JSONField('请求体', blank=True, default=dict)
    expected_result = models.TextField('期望结果', default='')
    priority = models.CharField('优先级', max_length=10, choices=PRIORITY_CHOICES, default='MEDIUM')
    allure = models.JSONField('Allure标注', blank=True, default=dict)
    api_args = models.JSONField('接口用例参数', blank=True, default=dict)  # 用例步骤（实际传参）
    extract = models.JSONField('数据提取', blank=True, default=dict)
    validate = models.JSONField('断言', blank=True, default=dict)
    created_time = models.DateTimeField('创建时间', auto_now_add=True, null=True)
    updated_time = models.DateTimeField('更新时间', auto_now=True)

    def to_yaml(self):
        """将用例数据转换为YAML格式"""
        case_data = {
            'title': self.name,
            'request': {
                'method': self.interface.method,
                'url': self.interface.url
            }
        }
        
        # 添加Allure标注
        if self.allure:
            if 'feature' in self.allure:
                case_data['feature'] = self.allure['feature']
            if 'story' in self.allure:
                case_data['story'] = self.allure['story']
        
        # 添加API参数
        if self.api_args:
            for key, value in self.api_args.items():
                case_data['request'][key] = value
        
        # 添加提取规则
        if self.extract:
            case_data['extract'] = self.extract
        
        # 添加断言规则
        if self.validate:
            case_data['validate'] = self.validate
            
        return yaml.dump(case_data, allow_unicode=True, sort_keys=False)

    def save_yaml(self, file_path=None):
        """将用例数据保存为YAML文件"""
        yaml_content = self.to_yaml()
        if not file_path:
            temp_dir = tempfile.mkdtemp()
            file_path = os.path.join(temp_dir, f"{self.id}_{self.name}.yaml")
            
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(yaml_content)
            
        return file_path

    class Meta:
        verbose_name = '测试用例'
        verbose_name_plural = '测试用例列表'

    def __str__(self):
        return self.name

class CaseExecutionRecord(models.Model):
    STATUS_CHOICES = [
        ('pending', '未执行'),
        ('running', '执行中'),
        ('success', '成功'),
        ('failed', '失败'),
    ]
    case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='executions')
    status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='pending')
    result = models.TextField(blank=True, null=True)
    report_url = models.CharField(max_length=255, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"用例{self.case.id}执行于{self.created_at}"